/**
 * Created by Mission on 16/10/10.
 */
//评论框键盘收起
function packupKeyboard() {
    $(".moreDiv").remove();
    $(".desc").blur();
}

$(function () {
    var max = 0;//选项数量
    var ischoose = 0;//是否多选状态boolean0,1
    var is_multiselect;//几项
    var isanony = 1;//是否匿名
    var cansee = 1;//是否发起人可见
    var status = 0;//0为保存，1为发布
    var index = 0;//跳转使用：0为保存，1为发布
    var cho_id = 0;//选项id：for拍照
    var isfull;//添加的选项标题是否全部写完
    var end_time, optionStr;
    //获取页面间的url的参数
    (function ($) {
        $.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        }
    })(jQuery);
    var vote_id = $.getUrlParam('vote_id');
    var url;
    console.log(vote_id);
    if (vote_id != null) {
        //如果有传入vote_id
        //草稿保存和发布url
        url = apiurl + "/vote/releaseorsave";
        //获取数据
        var vote_url = apiurl + "/vote/" + vote_id;
        var data = {
            user_id: user_id,
            token: token,
        };
        $.ajax({
            beforeSend: function () {
            },
            url: vote_url,
            type: "GET",
            data: data,
            success: function (d) {
                console.log(d);
                if (d.code == 1) {
                    if (d.msg == "202") {
                        //-----------------------------------------------
                        $('.token_iframe').show();
                    }
                } else {
                    var data = JSON.parse(d).data.voteVo;
                    $('.input1').val(INPUTEncode(data.vote_title));
                    $('.input2').val(INPUTEncode(data.vote_desc));
                    max = data.options.length;//选项个数
                    /**
                     * 添加传入的已有选项
                     */
                    for (var i = 0; i < max; i++) {
                        var option_pic = data.options[i].option_pic;
                        var add_html;
                        if (option_pic) {//不为空
                            add_html = "<div class='content-item'><div class='des'><div class='des-left'><img class='des-img' src='../img/sub.png'></div><div class='des-right'><label class='uploads'><img src='../img/upload-icon.png'class='xfile'></label> <form name='form' id='form" +
                                cho_id + "' enctype='multipart/form-data' method='post' hidden> <input type='file' name='img1' class='upload' id='upload' multiple='multiple'></form></div><div class='des-c'><input type='text' id='desc" + cho_id + "' class='desc' value='" + INPUTEncode(data.options[i].option_txt) + "' maxlength='50'name='ct-descri'/></div></div><div class='imglist' id='imglist" +
                                cho_id + "'><div class='img_based'>" +
                                "<img src='" + option_pic + "' class='img'>" +
                                "<img src='../img/delete.png' class='img_delete'>" +
                                "</div></div></div>";
                        } else {
                            add_html = "<div class='content-item'><div class='des'><div class='des-left'><img class='des-img' src='../img/sub.png'></div><div class='des-right'><label class='uploads'><img src='../img/upload-icon.png'class='xfile'></label> <form name='form' id='form" +
                                cho_id + "' enctype='multipart/form-data' method='post' hidden> <input type='file' name='img1' class='upload' id='upload' multiple='multiple'></form></div><div class='des-c'><input type='text' id='desc" + cho_id + "' class='desc' value='" + INPUTEncode(data.options[i].option_txt) + "' maxlength='50'name='ct-descri'/></div></div><div class='imglist' id='imglist" +
                                cho_id + "'></div></div>";

                        }
                        $('.ct-content').append(add_html);
                        cho_id++;//选项id+1
                    }
                    is_multiselect = data.is_multiselect;
                    if (is_multiselect == 1) {
                        ischoose = 0;
                        $('#multi-cho').attr("src", "../img/choose-off.png");
                        $('#most-cho').css("display", "none");
                        $('#most-cho').css("color", "#CCCCCC");
                        $('#subs').attr("src", "../img/sub_off.png");
                        $('#subs').unbind("click");
                        $('#adds').attr("src", "../img/add_off.png");
                        $('#adds').unbind("click");
                    } else {
                        ischoose = 1;
                        $('.most-num').text(is_multiselect);
                        $('#multi-cho').attr("src", "../img/choose-on.png");
                        $('#most-cho').css("display", "block");
                        $('#most-cho').css("color", "#323232");
                        $('#subs').attr("src", "../img/sub_on.png");
                        $('#adds').attr("src", "../img/add_on.png");
                        if (is_multiselect == 2) {
                            $('#subs').attr("src", "../img/sub_off.png");
                        }
                        if (is_multiselect == max) {
                            $('#adds').attr("src", "../img/add_off.png");
                        }
                    }
                    isanony = data.is_anonymous;
                    if (isanony == 1) {
                        $('#anony').attr("src", "../img/choose-off.png");
                    } else {
                        $('#anony').attr("src", "../img/choose-on.png");
                    }
                    cansee = data.is_view;
                    if (cansee == 1) {
                        $('#cansee').attr("src", "../img/choose-off.png");
                    } else {
                        $('#cansee').attr("src", "../img/choose-on.png");
                    }
                    if (data.end_time == 0) {
                        $(".endtime-input").val("");
                    } else {
                        var get_time = new Date(data.end_time);//截止时间
                        initDate(get_time);
                        $(".endtime-input").val(whole_time_horiz);
                    }
                }
            }
            ,
            error: function (d) {
                console.log(d);
            }
        });
    } else {//默认状态－－新建一个投票
        url = apiurl + "/vote";
        max = 0;
        ischoose = 0;//是否多选状态
        is_multiselect;//几项
        isanony = 1;//是否匿名
        cansee = 1;//是否发起人可见
        status = 0;//0为保存，1为发布


        $('#multi-cho').attr("src", "../img/choose-off.png");
        $('#most-cho').css("display", "none");
        $('#most-cho').css("color", "#CCCCCC");
        $('#subs').attr("src", "../img/sub_off.png");
        $('#subs').unbind("click");
        $('#adds').attr("src", "../img/add_off.png");
        $('#adds').unbind("click");


    }
    //绑时间控件
    selectDate($(".endtime-input"));
    //时间控件方法
    function selectDate(obj) {
        var currYear = (new Date()).getFullYear();
        var opt = {};
        opt.date = {preset: 'date'};
        opt.datetime = {preset: 'datetime'};
        opt.time = {preset: 'time'};
        opt.default = {
            theme: 'sense-ui', //皮肤样式
            display: 'modal', //显示方式
            mode: 'scroller', //日期选择模式
            lang: 'zh',
            startYear: currYear, //开始年份
            endYear: currYear + 10 //结束年份
        };
        var optDateTime = $.extend(opt['datetime'], opt['default']);
        obj.mobiscroll(optDateTime).datetime(optDateTime);
    }

    /**
     * 返回按钮－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－
     */
    $("#create_return").click(function () {
        location.href = "voteHome.html";
    });

    /**
     * 保存按钮－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－
     */
    // $('#save').click(function () {
    //
    //     $('#cbody').css('overflow', 'hidden');
    //     $('.dialogBg').show();
    // });
    /**
     * 保存按钮中的"是"与"否"－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－
     */
    // $(".btn-no").click(function () {
    //     $('.dialogBg').hide();
    //     $('#cbody').css('overflow', 'scroll');
    // });
    //.btn-yes=>#save 3月18号
    $('#save').click(function () {
        isfull = 0;
        $('.desc').each(function () {
            if (this.value != "" && this.value != null) {
                isfull++;
            }
        });
        var pop_up = $('.pop-up');
        if ($('.input1').val().replace(/\s+/g, "") == null || $('.input1').val().replace(/\s+/g, "") == "") {
            $('.input1').val("");
            pop_up_fn(pop_up, '标题不能为空');
        } else {
            status = 0;
            index = 0;
            $('#save').text("正在保存...");
            send("保存");

        }
    });
    $(document).on('input', '.input1', function () {
        var pop_up = $('.pop-up');
        var have = $(this).val();
        console.log("have：" + have.length);
        if (have.length == 21) {//当输入超过限制的时候取限制内的文字内容
            $(".input1").blur();
            pop_up_fn(pop_up, "输入字数已达上限");
            have = have.substring(0, 20);
            $(this).val(have);

        }
    });
    $(document).on('input', '.input2', function () {
        var pop_up = $('.pop-up');
        var have = $(this).val();
        console.log("have：" + have.length);
        if (have.length == 101) {//当输入超过限制的时候取限制内的文字内容
            $(".input2").blur();
            pop_up_fn(pop_up, "输入字数已达上限");
            have = have.substring(0, 100);
            $(this).val(have);

        }
    });

    $(document).on('input', '.desc', function () {
        var pop_up = $('.pop-up');
        var have = $(this).val();
        console.log("have：" + have.length);
        if (have.length == 51) {//当输入超过限制的时候取限制内的文字内容
            $(".desc").blur();
            pop_up_fn(pop_up, "输入字数已达上限");
            have = have.substring(0, 50);
            $(this).val(have);

        }
    });

    //添加选项 按钮
    $('.add-content').click(function () {
        var html = "<div class='content-item'><div class='des'><div class='des-left'><img class='des-img' src='../img/sub.png'></div><div class='des-right'><label class='uploads'><img src='../img/upload-icon.png'class='xfile'></label> <form name='form' id='form" +
            cho_id + "' enctype='multipart/form-data' method='post' hidden> <input type='file' name='img1' class='upload' id='upload' multiple='multiple'></form></div><div class='des-c'><input type='text' id='desc" + cho_id + "' class='desc' placeholder='输入文字描述（最多50字）' maxlength='51' name='ct-descri'/></div></div><div class='imglist' id='imglist" +
            cho_id + "'></div></div>";
        $('.ct-content').append(html);
        $("#desc" + cho_id).focus();
        cho_id++;//选项id+1
        max = max + 1;//总数量＋1
        if ($('#adds').attr("src") == "../img/add_off.png") {
            $('#adds').attr("src", "../img/add_on.png");
        }

    });
    //点击图片进行选择
    $(document).on('click', '.uploads', function () {
        $(this).parent().find(".upload").click();
    });
    // 拍照：监听input的change状态，上传图片
    $(document).on('change', '.upload', function (d) {

        var form_id = "#" + $(this).parent().attr("id");
        var list_id = "#" + $(this).parent().parent().parent().parent().find(".imglist").attr("id");
        console.log(list_id);
        var formdata = new FormData($(form_id)[0]);
        formdata.append("type", "0");
        formdata.append("names", "img");

        var file = this.files[0];
        if (file != undefined) {
            var file_name = file.name;
            var type = file_name.split(".");
            type = type[type.length - 1];
            if (checkImageType(file_name) == true) {
                $.ajax({
                    type: 'POST',
                    url: apiurl + '/global/upload',
                    data: formdata,
                    cache: false,
                    processData: false,
                    contentType: false,
                    mimeType: "multipart/form-data",
                    beforeSend: function () {
                        $(list_id).html("");
                        var img_html = "<div class='img_based'>" +
                            "<img src='../img/loading.gif' class='img'>" +
                            "<img src='../img/delete.png' class='img_delete'>" +
                            "</div>";
                        $(list_id).append(img_html);
                    },
                    success: function (d) {
                        console.log(d);
                        var data_url = JSON.parse(d).data;
                        $(list_id).find('.img').eq(0).attr("src", "http://" + data_url + "");
                    }
                });
            } else {
                $(".call_back_success").text("不支持该图片类型!").fadeIn();
                setTimeout(function () {
                    $(".call_back_success").fadeOut(1000);
                }, 1000);
            }
        }
        // var imgInput = $('.upload');
        // imgInput.replaceWith(imgInput.val('').clone(true));
    });
    //删除所选图片
    $(document).on('click', '.img_delete', function () {
        $(this).parent().remove();
    });
    // 删除选项
    $(document).on('click', '.des-left', function () {
        $(this).parent().parent().remove();
        max = max - 1;
        var s = parseInt($('.most-num').text());
        if (max < 2) {
            $('#multi-cho').attr("src", "../img/choose-off.png");
            $('#most-cho').css("display", "none");
            $('#most-cho').css("color", "#CCCCCC");
            $('#subs').attr("src", "../img/sub_off.png");
            $('#subs').unbind("click");
            $('#adds').attr("src", "../img/add_off.png");
            $('#adds').unbind("click");
            ischoose = 0;
        }
        else if (max <= s && max >= 2) {

            $('.most-num').text(max);
            if (max == 2) {
                $('#subs').attr("src", "../img/sub_off.png");
            }
            $('#adds').attr("src", "../img/add_off.png");

        } else if (max > s) {
            $('#adds').attr("src", "../img/add_on.png");
        }


    });
//是否匿名
    $('#anony').click(function () {
        if (isanony == 1) {
            $('#anony').attr("src", "../img/choose-on.png");
            isanony = 2;
        } else {
            $('#anony').attr("src", "../img/choose-off.png");
            isanony = 1;
        }
    });
//是否可见
    $('#cansee').click(function () {
        if (cansee == 1) {
            $('#cansee').attr("src", "../img/choose-on.png");
            cansee = 2;
        } else {
            $('#cansee').attr("src", "../img/choose-off.png");
            cansee = 1;
        }
    });
//是否多选
    $('#multi-cho').click(function () {
        if (max > 1) {
            if (ischoose == 1) {
                $('#multi-cho').attr("src", "../img/choose-off.png");
                $('#most-cho').css("display", "none");
                ischoose = 0;

            } else {
                $('#multi-cho').attr("src", "../img/choose-on.png");
                $('#most-cho').css("display", "block");
                $('#most-cho').css("color", "#323232");
                if (parseInt($('.most-num').text()) == 2) {
                    $('#subs').attr("src", "../img/sub_off.png");
                } else {
                    $('#subs').attr("src", "../img/sub_on.png");
                }
                if (parseInt($('.most-num').text()) == max) {
                    $('#adds').attr("src", "../img/add_off.png");
                } else {
                    $('#adds').attr("src", "../img/add_on.png");
                }
                ischoose = 1;
            }
        }
    });
    //多选数量"－"
    $(document).on('click', '#subs', function () {
        var t = parseInt($('.most-num').text());
        var n = t - 1;
        if (n < 2) {
            $('.most-num').text(t);
            $('#subs').attr("src", "../img/sub_off.png");
        } else if (n == 2) {
            $('.most-num').text(n);
            $('#subs').attr("src", "../img/sub_off.png");
            $('#adds').attr("src", "../img/add_on.png");
        } else {
            $('.most-num').text(n);
            $('#adds').attr("src", "../img/add_on.png");
        }
    });
    //多选数量"＋"
    $(document).on('click', '#adds', function () {
        var a = parseInt($('.most-num').text());
        var b = a + 1;
        if (b < max) {
            $('.most-num').text(b);
            $('#subs').attr("src", "../img/sub_on.png");
        } else {
            $('.most-num').text(max);
            $('#adds').attr("src", "../img/add_off.png");
            if (max > 2) {
                $('#subs').attr("src", "../img/sub_on.png");
            }
        }
    });
    /**
     * 发布按钮－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－
     */
    var is_in_publish = false;

    $('#fabuBtn').click(function () {

        if (is_in_publish == false){
            is_in_publish = true;
            var pop_up = $('.pop-up');
            //必须项判断
            isfull = 0;
            $('.desc').each(function () {
                if (this.value != "" && this.value != null) {
                    isfull++;
                }
            });
            if ($('.input1').val().replace(/\s+/g, "") == null || $('.input1').val().replace(/\s+/g, "") == "") {
                $('.input1').val("");
                pop_up_fn(pop_up, '标题不能为空');
                is_in_publish = false;
            } else if ($('.content-item').length <= 0) {
                pop_up_fn(pop_up, '请添加投票选项');
                is_in_publish = false;
            } else if (isfull < $('.desc').length) {
                pop_up_fn(pop_up, '添加的选项标题未完整');
                is_in_publish = false;
            } else if ($('.endtime-input').val() == "") {
                pop_up_fn(pop_up, '请设置截止时间');
                is_in_publish = false;
            } else if (new Date($('.endtime-input').val()).getTime() < new Date().getTime()) {
                pop_up_fn(pop_up, '截止时间不能小于当前时间');
                is_in_publish = false;
            } else if ($('.desc').length < 2) {
                pop_up_fn(pop_up, '请设置最少两个选择');
                is_in_publish = false;
            } else {
                status = 1;
                index = 1;
                $('#fabuBtn').find('.fb-span').text("正在发布...");
                send("发布");

            }
        }


    });
    /**
     * 提示popupwindow－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－
     */
    function pop_up_fn(obj, title) {
        if (obj.css("display") == "block") {

        } else {
            obj.text(title);
            obj.fadeIn();
            obj.fadeOut(3000);
        }

    }

    /**
     * 数据采集和发布投票接口－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－
     */
    function send(tiptext) {
        var pop_up = $('.pop-up');
        $('#cbody').css('overflow', 'hidden');
        $('.dialogBg').show();
        $("#toast_text").text(tiptext + "中...");
        if (ischoose == 0) {
            is_multiselect = 1;
        } else {
            is_multiselect = $('.most-num').text();
        }
        //输入截止时间
        if ($('.endtime-input').val() == "") {
            end_time = 0;
        } else {
            end_time = new Date($('.endtime-input').val()).getTime();
        }

        //选项
        optionStr = [];
        if ($('.desc').length > 0) {
            $(".desc").each(function (index) {
                var item = {
                    option_txt: HTMLEncode($(this).val()),
                    option_pic: $(this).parent().parent().parent().find('.imglist').find('.img').attr("src") ? $(this).parent().parent().parent().find('.imglist').find('.img').attr("src") : ""
                };
                optionStr.push(item);
            });
            optionStr = JSON.stringify(optionStr);
        }

        //如果有vote_id 在data里加进去
        if (vote_id != null && vote_id != "") {
            var data = {
                vote_id: vote_id,
                vote_title: HTMLEncode($('.input1').val()),
                vote_desc: HTMLEncode($('.input2').val()),
                user_id: user_id,
                group_id: group_id,
                is_multiselect: is_multiselect,
                is_anonymous: isanony,
                is_view: cansee,
                end_time: end_time,
                optionJson: optionStr,
                // picStr: img_str,
                status: status,
            };
            console.log(data);

            $.ajax({
                url: url,
                type: "PUT",
                data: data,

                success: function (d) {



                    console.log(d);
                    $('#save').text(tiptext);
                    $('.dialogBg').hide();
                    $('#cbody').css('overflow', 'scroll');
                    if (d.code == "1") {
                        $('#save').text("保存");
                        $('#fabuBtn').find('.fb-span').text("发布");
                        if ($('.crt-suc').css("display") == "block") {

                        } else {

                            $("#tip").text(d.msg);
                            $('.crt-suc').fadeIn("fast");
                            $('.crt-suc').fadeOut(2500);
                        }
                        is_in_publish = false;
                    } else {
                        $("#tip").text(tiptext + "成功！");
                        $('.crt-suc').fadeIn("fast");
                        $('.crt-suc').fadeOut(800);
                        if (index == 0) {
                            setTimeout(function () {
                                location.href = "voteHome.html?index=0";
                            }, 800);
                        } else if (index == 1) {
                            setTimeout(function () {
                                location.href = "voteHome.html?index=1";
                            }, 800);
                        }
                    }

                },
                error: function (d) {
                    $('.dialogBg').hide();
                    $('#cbody').css('overflow', 'scroll');
                    $('#save').text("保存");
                    pop_up_fn(pop_up, '出错了');
                    console.log(d);
                    is_in_publish = false;
                }
            });
        } else {
            var data = {
                vote_title: HTMLEncode($('.input1').val()),
                vote_desc: HTMLEncode($('.input2').val()),
                user_id: user_id,
                group_id: group_id,
                is_multiselect: is_multiselect,
                is_anonymous: isanony,
                is_view: cansee,
                end_time: end_time,
                optionJson: optionStr,
                // picStr: img_str,
                status: status,
            };
            console.log(data);
            $.ajax({
                url: url,
                type: "POST",
                data: data,

                success: function (d) {
                    $('.dialogBg').hide();
                    $('#cbody').css('overflow', 'scroll');
                    $('#fabuBtn').find('.fb-span').text(tiptext);
                    if (d.code == "1") {
                        $('#save').text("保存");
                        if ($('.crt-suc').css("display") == "none") {

                        } else {
                            $("#tip").text(d.msg);
                            $('.crt-suc').fadeIn("fast");
                            $('.crt-suc').fadeOut(2500);
                        }
                        is_in_publish = false;
                    } else {
                        $("#tip").text(tiptext + "成功！");
                        $('.crt-suc').fadeIn("fast");
                        $('.crt-suc').fadeOut(800);
                        if (index == 0) {
                            setTimeout(function () {
                                location.href = "voteHome.html";
                            }, 800);
                        } else if (index == 1) {
                            setTimeout(function () {
                                location.href = "voteHome.html?index=1";
                            }, 800);
                        }
                    }

                },
                error: function (d) {

                    $('.dialogBg').hide();
                    $('#cbody').css('overflow', 'scroll');
                    $('#save').text("保存");
                    pop_up_fn(pop_up, '出错了');
                    console.log(d);
                    is_in_publish = false;
                }
            });
        }


    }

    //输入框高度判断
    $(document).on('focus', '.desc', function (e) {
        var rowCount = $(this).attr("id").replace("desc", "");
        var divHeight = $(".ct-title").outerHeight(true) + $(".ct-type").outerHeight(true) + $(".add-content").outerHeight(true);//

        for (var i = 0; i <= rowCount; i++) {
            var classId = "desc" + i;
            divHeight = divHeight + $("#" + classId).parent().parent().parent().outerHeight(true);
        }

        var documentHeight = $("#create_header").outerHeight(true) + $(".ct").outerHeight(true);  //整个html高度
        var windowHeight = $(window).height();  //屏幕高度
        var keyboardHeight = windowHeight / 2 + $("#create_header").outerHeight(true);  //半屏 + 导航
        var scrollHeight = divHeight + keyboardHeight - windowHeight;

        console.log(divHeight);

        if (divHeight > windowHeight / 2) {
            //需要滑动
            var canScrollHeight = documentHeight - windowHeight;
            console.log(canScrollHeight);
            console.log(scrollHeight);
            if (canScrollHeight < scrollHeight) {
                //滑动距离不够
                var moreHeight = (scrollHeight - canScrollHeight) / windowHeight * 100 + 'vh';
                console.log(moreHeight);
                $(".inputDiv").append('<div class="moreDiv" style="width: 100%;height: ' + moreHeight + '"></div>');
                // $(".inputDiv").css("height", "" + moreHeight + "");
            }

            window.scrollTo(0, scrollHeight);
        }
    });


});